package com.sx.netty.nio.Demo02_GroupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @Author ShuXin
 * @Description 群聊系统客户端的编写
 * @Date 2020/11/9 15:11
 */
public class GroupChatClient {
    //    定义相关属性
    private final String HOST = "127.0.0.1";
    private final Integer PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    //    构造器，完成初始化工作
    public GroupChatClient() throws IOException {
//        获取selector
        selector = Selector.open();
//        连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
//        设置成非阻塞
        socketChannel.configureBlocking(false);
//        将channel注册到selector上
        socketChannel.register(selector, SelectionKey.OP_READ);
//        获取到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + "\tis Ok！！！");
    }

    //    向服务器发送消息
    private void sendMsg(String msg) {
        msg = username + "说:\t" + msg;

        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //    读取服务端发送的消息
    private void readMsg() {
        try {
            int select = selector.select();
            if (select > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
//                    判断key的类型
                    if (key.isReadable()) {
//                        获取相应的通道
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
//                        将通道的内容读取到buffer中
                        channel.read(buffer);
//                        将的buffer中的内容转换成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                    iterator.remove();
                }
            } else {
                System.out.println("暂时没有可用的通道...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    启动客户端
    public static void main(String[] args) throws IOException {
        GroupChatClient client = new GroupChatClient();
//        创建一个线程读取从服务端发送的消息
        new Thread(() -> {
            while(true){
                client.readMsg();
                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        发送消息
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String msg = scanner.nextLine();
            client.sendMsg(msg);
        }
    }
}
